package com.xjtu.duansheli.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.duansheli.entity.CategoriesInfo;
import com.xjtu.duansheli.exception.MyException;
import com.xjtu.duansheli.mapper.CategoriesInfoMapper;
import com.xjtu.duansheli.service.CategoriesInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 漩涡鸣人
 * @since 2020-10-24
 */
@Service
public class CategoriesInfoServiceImpl extends ServiceImpl<CategoriesInfoMapper, CategoriesInfo> implements CategoriesInfoService {

    @Autowired
    private CategoriesInfoMapper categoriesInfoMapper;

    @Override
    public List<CategoriesInfo> getAllCategories(int current, int size) {
        Page<CategoriesInfo> page = new Page<>(current,size);
        categoriesInfoMapper.selectPage(page, null);
        System.out.println(page.getTotal());
        return page.getRecords();
//        List<CategoriesInfo> categoriesInfos = categoriesInfoMapper.selectList(null);
//        if (categoriesInfos.size() == 0) {
//            throw new MyException(500, "数据库中无数据！");
//        }
//        return categoriesInfos;
    }

    @Override
    public CategoriesInfo getCategoryByid(Long cid) {
        CategoriesInfo categoriesInfo = categoriesInfoMapper.selectById(cid);
        if (categoriesInfo == null) {
            throw new MyException(500, "不存在该商品类别记录！");
        }
        return categoriesInfo;
    }

    @Override
    public int addCategory(CategoriesInfo category) {
        try{
            return categoriesInfoMapper.insert(category);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException(500,"添加商品类别失败！");
        }
    }

    @Override
    public int updateCategory(CategoriesInfo category) {
        try{
            return categoriesInfoMapper.updateById(category);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException(500,"更新商品类别失败！");
        }
    }

    @Override
    public int deleteCategory(Long cid) {
        try{
            return categoriesInfoMapper.deleteById(cid);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException(500,"删除商品类别失败！");
        }
    }

    @Override
    public int getTotal() {
        return categoriesInfoMapper.selectCount(null);
    }
}
